﻿using EvaluationSystem.ViewModels;

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace EvaluationSystem.Utils
{
    public class ExcelUtil
    {
        public static string WriteExcel(IList<EvalInfoExcelVM>? list, string filename)
        {
            // NPOI
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("评价表");
            //创建行

            // 写头部
            {
                IRow row = sheet.CreateRow(0); //i表示了创建行的索引，从0开始
                row.CreateCell(0).SetCellValue("学生id");
                row.CreateCell(1).SetCellValue("学生名");
                row.CreateCell(2).SetCellValue("课程名");

                int col = 3;
                foreach (var item in list?[0].Evals)
                {
                    row.CreateCell(col).SetCellValue(item.Key);
                    col++;
                }
            };

            int rowIndex = 1;
            foreach (var item in list)
            {
                IRow row = sheet.CreateRow(rowIndex); //i表示了创建行的索引，从0开始
                row.CreateCell(0).SetCellValue(item.StudentID);
                row.CreateCell(1).SetCellValue(item.StudentName);
                row.CreateCell(2).SetCellValue(item.CourseName);

                int col = 3;
                foreach (var ite in item.Evals)
                {
                    row.CreateCell(col).SetCellValue(ite.Value);
                    col++;
                }
                rowIndex++;
            }
            //表格制作完成后，保存
            //创建一个文件流对象
            //var path = Path.Combine(Path.GetTempPath(), filename);
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
            using (FileStream fs = System.IO.File.Open(path, FileMode.OpenOrCreate))
            {
                workbook.Write(fs);
                //最后记得关闭对象
                workbook.Close();
            }

            return path;
        }
    }
}
